import { VideoType } from '@renderer/types/store'
import { ref } from 'vue'
import { useSettingsStoreHook } from '@renderer/store'
import { VideoState } from '@renderer/enums/settingEnum'

interface UseSelectFileOptions {
  accept?: string
  multiple?: boolean
  onSelect?: (files: File[]) => void
  onError?: (error: Error) => void
}

export function useSelectFile(options: UseSelectFileOptions = {}) {
  const { accept = '.mp4,.avi,.mov,.mkv,.flv', multiple = false, onSelect, onError } = options

  const selectedFilePaths = ref<string[]>([])
  const isDragging = ref(false)
  const fileInputRef = ref<HTMLInputElement | null>(null)
  const thumbnailUrl = ref<string | null>(null)

  const { ipc, getPathForFile } = window
  const settingsStore = useSettingsStoreHook()

  const generateFilesForPaths = (paths: string[]): Promise<File[]> => {
    return Promise.all(
      paths.map(async (path) => {
        const response = await fetch(`file://${path}`)
        const blob = await response.blob()
        // 处理文件名中的反斜杠
        const fileName = path.split(/[\\/]/).pop() || 'file'
        const file = new File([blob], fileName, { type: blob.type })
        file.path = path
        return file
      })
    )
  }

  // 处理文件列表
  const processFiles = async (files: File[]): Promise<VideoType[]> => {
    return Promise.all(
      files.map(async (file) => {
        const thumbnail = await generateThumbnail(file)
        const resolution = await getVideoResolution(file)
        return {
          name: file.name,
          type: file.type,
          size: file.size,
          path: file.path,
          progress: 0,
          state: VideoState.READY,
          thumbnail,
          resolution
        } as VideoType
      })
    )
  }

  // 新增：获取视频分辨率
  const getVideoResolution = (file: File): Promise<{ width: number; height: number }> => {
    return new Promise((resolve) => {
      if (!file.type.startsWith('video/')) {
        resolve({ width: 0, height: 0 })
        return
      }

      const video = document.createElement('video')
      video.preload = 'metadata'
      const url = URL.createObjectURL(file)
      video.src = url

      video.onloadedmetadata = () => {
        resolve({
          width: video.videoWidth,
          height: video.videoHeight
        })
        URL.revokeObjectURL(url)
      }

      video.onerror = () => {
        resolve({ width: 0, height: 0 })
        URL.revokeObjectURL(url)
      }
    })
  }

  // 通过点击按钮选择文件
  const selectFile = async () => {
    try {
      const result = await ipc.file.selectFile({
        accept
      })

      if (result.success && result.filePaths) {
        // 处理文件并生成缩略图
        const files = await generateFilesForPaths(result.filePaths)
        const filesWithThumbnails = await processFiles(files)
        settingsStore.files = filesWithThumbnails

        if (onSelect) {
          onSelect(settingsStore.files.map((file) => file as File))
        }
      }
    } catch (error) {
      if (onError && error instanceof Error) {
        onError(error)
      }
    }
  }

  // 获取视频缩略图
  const generateThumbnail = async (file: File): Promise<string | null> => {
    if (!file.type.startsWith('video/')) return null
    return new Promise((resolve) => {
      try {
        const video = document.createElement('video')
        video.preload = 'metadata'
        const url = URL.createObjectURL(file)
        video.src = url

        video.onloadedmetadata = () => {
          video.currentTime = Math.min(video.duration * 0.1, 3)
          video.onseeked = () => {
            const canvas = document.createElement('canvas')
            canvas.width = video.videoWidth
            canvas.height = video.videoHeight
            const ctx = canvas.getContext('2d')
            if (ctx) {
              ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
              const thumbnailDataUrl = canvas.toDataURL('image/jpeg', 0.7)
              URL.revokeObjectURL(url)
              resolve(thumbnailDataUrl)
            } else {
              URL.revokeObjectURL(url)
              resolve(null)
            }
          }
        }

        video.onerror = () => {
          URL.revokeObjectURL(url)
          resolve(null)
        }
      } catch (error) {
        console.error('生成缩略图失败:', error)
        resolve(null)
      }
    })
  }

  // 处理文件选择变更
  const handleFileChange = async (event: Event) => {
    const input = event.target as HTMLInputElement
    if (input.files && input.files.length > 0) {
      const files = Array.from(input.files)

      const filesWithThumbnails = await processFiles(files)
      settingsStore.files = multiple ? filesWithThumbnails : [filesWithThumbnails[0]]

      if (onSelect) {
        onSelect(settingsStore.files.map((file) => file as File))
      }

      // 重置input值，确保同一文件可以再次选择
      input.value = ''
    }
  }

  // 处理文件拖放
  const handleDragOver = (event: DragEvent) => {
    event.preventDefault()
    isDragging.value = true
  }

  const handleDragLeave = (event: DragEvent) => {
    event.preventDefault()
    isDragging.value = false
  }

  const handleDrop = async (event: DragEvent) => {
    event.preventDefault()
    isDragging.value = false

    if (event.dataTransfer?.files.length) {
      try {
        const files = Array.from(event.dataTransfer.files)
        // 获取文件路径
        const path = files.map((file) => getPathForFile(file))

        if (path) {
          // 验证文件
          const result = await ipc.file.validateFiles({
            filePaths: path,
            accept
          })

          if (result.success && result.filePaths) {
            selectedFilePaths.value = result.filePaths

            // 将文件转换为File对象
            const processedFiles = await generateFilesForPaths(result.filePaths)

            // 处理文件并生成缩略图
            const filesWithThumbnails = await processFiles(processedFiles)
            settingsStore.files = multiple ? filesWithThumbnails : [filesWithThumbnails[0]]

            if (onSelect) {
              onSelect(settingsStore.files.map((file) => file as File))
            }
          } else {
            throw new Error(result.error || '文件验证失败')
          }
        } else {
          throw new Error('无法获取文件路径')
        }
      } catch (error) {
        if (onError && error instanceof Error) {
          onError(error)
        }
      }
    }
  }

  // 绑定拖放区域
  const setupDropArea = (element: HTMLElement) => {
    if (element) {
      element.addEventListener('dragover', handleDragOver)
      element.addEventListener('dragleave', handleDragLeave)
      element.addEventListener('drop', handleDrop)

      return () => {
        element.removeEventListener('dragover', handleDragOver)
        element.removeEventListener('dragleave', handleDragLeave)
        element.removeEventListener('drop', handleDrop)
      }
    }
    return undefined
  }

  // 暴露出文件选择方法和状态
  return {
    isDragging,
    fileInputRef,
    thumbnailUrl,
    selectFile,
    handleFileChange,
    setupDropArea,
    generateThumbnail
  }
}
